﻿using Zpb;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Threading;
using UtilPublic;
using UtilPublic.Serialization;
using UtilWpf;
using gpb = global::Google.Protobuf;
using ConfClient;

namespace client
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            TimedInit();

            Conf.InitConf();
        }
        public static SocketClient socket = new();
        //主窗口
        public static MainWindow WdMain = null;
        public static PageDebug PageDebug = null;
        public static PagePlayer PagePlayer = null;

        public static void Send<T>(EPid pid, T msg) where T : gpb.IMessage => socket.Send(pid, msg);
        public static void Send(EPid pid) => socket.Send(pid);

        #region 定时器
        private Timer aTimer = null;
        private delegate void TimerDispatcherDelegate();
        private void TimedInit()
        {
            aTimer = new Timer(200);
            aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            aTimer.Interval = 200;
            aTimer.Enabled = true;
        }
        private void OnTimedEvent(object sender, EventArgs e)
        {
            this.Dispatcher.Invoke(DispatcherPriority.Normal,
                new TimerDispatcherDelegate(MsgHandle));
        }
        private static void MsgHandle()
        {
            while (socket.ListMsg.TryDequeue(out var msg))
            {
                WdMain.MsgHandle(msg);
            }
        }
        #endregion
        #region 公共
        public static string TxtDebug = "";
        public static void DebugInfo(object o)
        {
            MessageBox.Show($"{o}", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
        }
        public static void DebugError(object o)
        {
            MessageBox.Show($"{o}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
        }
        public static void DebugDebug(object o)
        {
            if (PageDebug == null)
            {
                TxtDebug = $"{o}\r\n{TxtDebug}";
            }
            else
            {
                PageDebug.TextBoxDebug.Text = $"{o}\r\n{PageDebug.TextBoxDebug.Text}";
                PageDebug.TextBoxText.Text = $"{o}";
            }
        }
        public static void Error(object o)
        {
            Application.Current.Dispatcher.Invoke(delegate {
                DebugError(o);
            });
        }
        public static void Debug(object o)
        {
            Application.Current.Dispatcher.Invoke(delegate {
                DebugDebug(o);
            });
        }
        #endregion

        
    }
}
